<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: songaimin@clcw.com.cn  Blog:http://blog.csdn.net/samxx8        |
// +------------------------------------------------------------------------+
//
namespace AuctionCore\AuctionOrder;

use AuctionCore\CarDealer\Dealer;
use AuctionCore\CarResource\CarSource;
use AuctionCore\ChangeOrder\ChangeOrder;
use AuctionCore\PurchaseOrder\PurchaseOrder;
use AuctionCore\System\AuctionException;
use AuctionCore\Common\Util;
use AuctionCore\CarResource\Car;
use AuctionCore\CarResource\CarModel;
use AuctionCore\Other\Address;
use AuctionCore\Other\Channel;
use AuctionCore\System\SystemConf;


/**
 * 拍单功能类
 *
 * @author   Administrator
 */
class AuOrder
{

    protected $order_id = null;

    /**
     * 构造
     *
     * @param  int $order_id 拍单编号 或 拍单id
     *
     */
    public function __construct($order_no_or_id)
    {
        if (is_numeric($order_no_or_id)) {
            $this->order_id = $order_no_or_id;
        } else {
            $r = M('order')->field('order_id')->where("order_no='{$order_no_or_id}'")->find();
            if ($r && count($r) > 0) {
                $this->order_id = $r['order_id'];
            } else {
                AuctionException::make_throw('700002');
            }
        }
    }

    /**
     * 调用车辆对象的生成拍单方法
     * 静态方法,生成拍单，返回新的拍单id
     *
     * @param  int $car_id 车辆id
     * @param  array $order 拍单信息
     *
     * @return  int
     */
    public static function create($car_id, $order)
    {
        $car = new Car($car_id);
        try {
            $res = $car->create_order($order);
        } catch (\Exception $e) {
            $res = false;
        }
        return $res;
    }

    /**
     * 车主前台自主确认成交
     *
     * @return   boolean
     */
    public function confirm_trade()
    {
        $up_info = array('is_self_confirm' => 1);
        $ok = $this->update($up_info);
        if ($ok === false) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 拍单详情，以及拍单状态等。
     *
     * @return array
     */
    public function detail()
    {
        return M('order')->where("order_id='{$this->order_id}'")->find();
    }

    /**
     * 当前是否有未结束的场次。
     *
     * @return array
     */
    public function get_scene_live()
    {
        //return M('order_scene')->where("status='2' and starttime like '".date('Y-m-d')."%'")->find();
    }

    /**
     * 拍单场次。
     *
     * @return   Array
     */
    public function get_scene($scene_id)
    {
        return M('order_scene')->where("scene_id='" . $scene_id . "'")->find();
    }

    private function check_last_bid_dealer()
    {
        return M('bid_log')->where("order_id='" . $this->order_id . "'")->order("bid_id DESC")->limit('0,1')->getField('dealer_id');
    }

    /**
     * 投标出价，只接受高于起拍价的出价，每车/每车商只能投标一次
     *
     * @param    int $dealer_id 车商id
     * @param    int $price 投标出价，人民币
     * @param    int $dev_type 出价设备（0 web,1 android ,2ios)
     *
     * @return   Array
     */
    public function bid_price($dealer_id, $price, $dev_type = 0)
    {

        //基本数据验证
        if (empty($this->order_id)) {
            AuctionException::make_throw('700002');
        }
        if (empty($dealer_id)) {
            AuctionException::make_throw('500001');
        }
        if (empty($price)) {
            AuctionException::make_throw('700005');
        }
        //检查价格是否合法
        $order = $this->detail();
        if ($price <= $order['bid_start_price']) {
            AuctionException::make_throw('700007');
        }
        //检查拍单状态是否为投标中
        if ($order['status'] != '3') {
            AuctionException::make_throw('700041');
        }

        $car = new \AuctionCore\CarResource\Car($order['car_id']);
        $car_info = $car->detail();

        $according = max($order['reserve_price'], $car_info['suggest_max_price']);
        if (($price) > ($according * 1.2)) {
            AuctionException::make_throw('700033');  //出价超高
        }

        //一个人不能持续出价
//            $last_bid_dealer_id = $this->check_last_bid_dealer();
//            if($dealer_id == $last_bid_dealer_id){
//                AuctionException::make_throw('700031');
//            }

        //更新拍单表bid_best_price
//            if($price > $order['bid_best_price']){
//                $this->update(array('bid_best_price'=>$price,'bid_best_dealer_id'=>$dealer_id));
//            }

        $data = array();
        $data['order_id'] = $this->order_id;
        $data['dealer_id'] = $dealer_id;
        $data['price'] = $price;
        $data['createtime'] = date('Y-m-d H:i:s');
        $data['dev_type'] = $dev_type;

//            //查重
//            $c = M('bid_log')->where("order_id='".$this->order_id."' and dealer_id='".$dealer_id."'")->find();
//            if(!empty($c)){
//                AuctionException::make_throw('700006');
//            }

        //事务开始
        M()->startTrans();
        $flag = true;
        $error = '';
        //冻结保证金
        $asset = new \AuctionCore\CarDealer\AssetCenter($dealer_id);
        $bail = M('setting')->where("name='BAIL'")->getField('value');
        try {
            $asset->freeze($this->order_id, $bail);
        } catch (\Exception $e) {
            $error = ',' . $e->getMessage();
            $flag = false;
        }
        $res = M('bid_log')->add($data);
        if ($res) {
            $msg = '投标出价';
        } else {
            $msg = '投标出价保存失败';
            $flag = false;
        }
        if ($flag) {
            M()->commit();
        } else {
            M()->rollback();
            \Think\Log::record($msg . ' ' . $error);
        }
        //车商操作日志
        $log = array('order_id' => $this->order_id, 'dealer_id' => $dealer_id, 'action' => $msg . ',price:' . $price, 'createtime' => date('Y-m-d H:i:s'));
        M('dealer_log')->add($log);

        return array('flag' => $flag, 'error' => $msg . ' ' . $error);
    }

    /**
     * 竞标出价，实现方式：长连接实时显示竞标价格.
     * 返回array格式如下:
     * {
     *  status=>:true成功false失败并在info给出信息
     *  ,info=>{
     * process:竞价进度
     * remaintime=>剩余时间,biding_num=>竞价手次,cur_price=>当前价格,you_bidding=>你的竞标价,commision=>交易佣金,Transfer_fee=>过户费用,amount=>合手价格,conpon=>代金使用,last_sum=>最终价格]
     * }
     * 竞价进度：
     * 1 出价成功
     * 2 出价成功并已过投标最高价
     * 3 竞拍已结束并成交待确认
     * 4 流拍，即竞拍结束时最高竞拍价低于最高投标价
     *
     * 竞拍中：
     * a.竞价时间暂定120秒，0秒之前车商可以出价
     * b.出价后，价格高于”投标阶段最高价“的，页面显示”已过投标最高价“提示。
     * 结束后：
     * c.0秒之后，即为竞拍结束
     * d.竞拍结束后，竞拍价格高于”投标阶段最高价“的，拍单状态更新为”成交待确认"。否则状态更新为"流拍"
     *
     * @param    int $dealer_id 车商id
     * @param    int $org_price 出价基础价
     *
     * @param    int $add_price 竞拍加价，人民币
     *                            同时依次算出：竞拍的第1，2，3 前三高价信息存入拍单
     * @param int $dev_type 出价设备
     *
     * @return   array 出价详情
     */
    public function bidding_price($dealer_id, $org_price, $add_price, $dev_type = 0)
    {
        $order_info = $this->detail();
        $db_org_price = $order_info['bidding_best_price'];  //库里基础价
        $start_price = $order_info['bid_start_price'];//起拍价
        if ($db_org_price == 0) {
            $db_org_price = $start_price;
        }

        $car = new \AuctionCore\CarResource\Car($order_info['car_id']);
        $car_info = $car->detail();

        $according = max($order_info['reserve_price'], $car_info['suggest_max_price']);
        if (($db_org_price + $add_price) > ($according * 1.2)) {
            AuctionException::make_throw('700033');  //出价超高
        }

        if ($order_info['status'] != 4) { //竞标中判断
            AuctionException::make_throw('700009');
        }
        if ($db_org_price != $db_org_price) {//此基价是否已有人出价
            AuctionException::make_throw('700008');
        }

        if ($order_info['bidding_best_dealer_id'] == $dealer_id) {
            $car = new Car($order_info['car_id']);
            $car_info = $car->detail();
            if ($org_price > $order_info['reserve_price']) {
                //竞标中请等待别人出价
                AuctionException::make_throw('700032');
            }
        }

        $redis = new \AuctionCore\Common\PhpRedis();
        $keyArr = [
            'order_id' => $this->order_id,
            'org_price' => $org_price
        ];
        $lock_key = getRedisKeyByCode('REDIS_KEY','100013',$keyArr);
        //$lock_key = 'bidding_' . $this->order_id . '_' . $org_price . '_lock';
        if (!$redis->lock($lock_key))
            AuctionException::make_throw('700008');

        /******************************************存储过程方式********************************************/
        $setting = new AuctionSetting();
        $set_info = $setting->detail_by_name('BAIL');
        $freeze_price = $set_info['value'];
        //改为存储过程方式
        $order_id = $this->order_id;
        $m = M();
        $r_num = rand(10000, 9999);
        $sql = "call `paimai_bid`('{$dealer_id}', '{$order_id}', '{$org_price}','{$add_price}', '{$freeze_price}', '',@ret_{$r_num});";
//echo $sql;exit;
        $r = $m->execute($sql);
        $redis->unlock($lock_key);

        $r_code = -1;
        $r = $m->query("select @ret_{$r_num};");
        $r_code = $r[0]["@ret_{$r_num}"];

        /*   dump($r);
           echo $sql;
           dump($r_code);exit;*/
        if ($r_code < 4) {
            switch ($r_code) {
                case 0:
                    AuctionException::make_throw('700022'); //0用户没有开通拍卖
                    break;
                case 1:
                    AuctionException::make_throw('700023'); //1车源不在拍卖状态
                    break;
                case 2:
                    AuctionException::make_throw('700024'); //2保证金不够
                    break;
                case 3:
                    AuctionException::make_throw('700025'); //3出价不合法（该价别人已出）
                    break;
                default:
                    AuctionException::make_throw('700021'); //-1异常错误（默认）
                    break;
            }
        }
        //更新出价记录的出价设备
        if ($dev_type > 0) {
            $m->execute("UPDATE au_bidding_log SET dev_type='" . $dev_type . "' WHERE order_id='" . $order_id . "' AND dealer_id='" . $dealer_id . "' AND before_price='" . $org_price . "'");
        }
        //
        $bidding_info = $this->get_bidding_info();

        /*$log = M('bidding_log')->where(" order_id='{$order_id}' AND dealer_id='{$dealer_id}' ")->order(' bidding_id DESC ')->limit(1)->find();
        $log['after_price'] = format_money($log['after_price']);
        $log['bid_max_price'] = $log['after_price']>$order_info['bid_best_price']?'已过':'未过';
        $bidding_info['log'] = $log;*/

        $bidding_info['dealer_id'] = $dealer_id;
        //TODO PUSH 出价信息到 redis  
        $ok = Util::redis_publish('bidding_msg', json_encode($bidding_info, true));

        return $bidding_info;

        /***************************************php处理方式*********************************************/
        // //保证金处理
        // $dealer_bail_log = M('dealer_bail_log');

        // //更新拍单竞价最高价
        // $max_price = ($org_price+$add_price);
        // $au_info = array('bidding_best_price'=>$max_price,'last_time'=>date("Y-m-d H:i:s",time()));
        // $au_m = M('order');
        // $au_where = 'order_id=\''.$this->order_id.'\' and bidding_best_price=\''.$org_price.'\'';
        // $eff = $au_m->where($au_where)->save($au_info);
        // if(!(intval($eff)>0)){
        //     AuctionException::make_throw('700008');
        // }  

        // $log_info = array(        
        //     'dealer_id'=>$dealer_id  //int(10)       车商id             
        //     ,'order_id'=>$this->order_id  //int(10)       拍单号            
        //     ,'before_price'=>$org_price  //double(10,2)  竞拍出价前价格
        //     ,'append_price'=>$add_price  //double(10,2)  竞拍加价         
        //     ,'after_price'=>$max_price  //double(10,2)  竞拍出价后价格
        //     ,'createtime'=>date("Y-m-d H:i:s",time())  //datetime      竞拍出价时间   
        // );        
        // $bidding_m = M('bidding_log');
        // $log_id = $bidding_m->add($log_info);

        // if(intval($log_id)>0){
        //     //车商操作日志 
        //     $log = array('order_id'=>$this->order_id,'dealer_id'=>$dealer_id,'action'=>'竞价出价'.',price:'.$max_price,'createtime'=>date('Y-m-d H:i:s'));
        //     M('dealer_log')->add($log);

        //     return true;
        // }else{
        //     return false;
        // }

    }

    /**
     * 添加一条竞拍出价记录
     *
     * @param array $data
     *
     * @return bool|mixed
     */
    public function add_bidding_log($data = array())
    {
        if (empty($data)) {
            return false;
        }
        return M('bidding_log')->add($data);
    }

    /**
     * 添加一条投标出价记录
     *
     * @param array $data
     *
     * @return bool|mixed
     */
    public function add_bid_log($data = array())
    {
        if (empty($data)) {
            return false;
        }
        return M('bid_log')->add($data);
    }

    /**
     * 获得出价信息
     */
    public function get_bidding_info()
    {
        $order_id = $this->order_id;
        $m = M();
        $sql = "SELECT order_id,order_no,bid_start_price,bid_best_price,bidding_best_price,bid_best_dealer_id
        ,bidding_best_dealer_id,IF(bidding_best_price=0,bid_start_price,bidding_best_price) as price 
        ,UNIX_TIMESTAMP(bidding_start_time)+IF(act_elapsed_time>est_elapsed_time,act_elapsed_time,est_elapsed_time) - UNIX_TIMESTAMP(NOW()) AS left_time  
        FROM au_order WHERE order_id='{$order_id}';";
        $r1 = $m->query($sql);
        if ($r1[0]['left_time'] <= 0)
            $r1[0]['left_time'] = 0;
        $sql = "SELECT COUNT(*) AS bidding_num,COUNT(DISTINCT dealer_id ) AS dealer_num  FROM au_bidding_log WHERE order_id='{$order_id}';";
        $r2 = $m->query($sql);
        return (array_merge($r1[0], $r2[0]));
    }

    /**
     * 开始竞拍
     */
    public function start_bidding()
    {
        //TODO 开始竞拍
        $up_info = array('status' => 4, 'bidding_start_time' => date("Y-m-d H:i:s", time())); //更改为"竞拍中"
        $ok = $this->update($up_info);
    }

    /**
     * 结束竞拍
     */
    public function end_bidding()
    {

        //找出第一高价车商
        $max_bid = M('bid_log')->where('order_id=' . $this->order_id)->order('price desc , createtime desc')->limit(1)->select();
        $max_log = $max_bid[0];
        $max_bidding = M('bidding_log')->where('order_id=' . $this->order_id)->order('after_price desc , createtime desc')->limit(1)->select();
        if (intval($max_bidding['after_price']) > intval($max_bid['price'])) {
            $max_log = $max_bidding[0];
        }

        //记录拍单成功车商
        $add_info = array();
        $add_info['dealer_id'] = $max_log['dealer_id'];
        $add_info['order_id'] = $this->order_id;
        $add_info['createtime'] = date("Y-m-d H:i:s", time());
        $ok = M('dealer_auctioned')->add($add_info);
        //更改拍单状态
        $up_info = array('status' => 5, 'bidding_end_time' => date("Y-m-d H:i:s", time())); //更改为"成交待确认"
        $ok = $this->update($up_info);
    }

    /**
     * 拍单审核通过
     *
     * @param    int $emp_id 员工ID
     *
     * @return   boolean
     */
    public function audit_success($emp_id)
    {
        //数据有效性验证
        if (empty($emp_id)) {
            AuctionException::make_throw('300007');
        }
        $now = date('Y-m-d H:i:s');
        $up_info = array('status' => 3, 'bid_start_time' => $now, 'last_time' => $now);//投标中
        $res = $this->update($up_info);
        //操作日志
        $log = array('order_id' => $this->order_id, 'emp_id' => $emp_id, 'action' => '上拍审核通过');
        \AuctionCore\System\SystemLog::add($log);
        return $res;
    }

    /**
     * 拍单审核驳回
     *
     * @param    array $data 审核数据 $data['f'] = 1 点[详细审核]后 页面加个隐藏变量f=1，此时备注为必填项
     *
     * @return   boolean
     */
    public function audit_reject($data)
    {

        //数据有效性验证
        $data['order_id'] = $this->order_id;
        if (empty($data['emp_id'])) {
            AuctionException::make_throw('300007');
        }
        if (!empty($data['f']) && empty($data['remark_reject'])) {
            AuctionException::make_throw('500009');
        }
        $up_info = array('status' => 2, 'last_time' => date('Y-m-d H:i:s'), 'remark_reject' => $data['remark_reject']);//2审核驳回
        $res = $this->update($up_info);
        //操作日志
        $log = array('order_id' => $this->order_id, 'emp_id' => $data['emp_id'], 'action' => '上拍审核驳回');
        \AuctionCore\System\SystemLog::add($log);
        return $res;

    }

    /**
     * 跟踪日志
     *
     * @return   array
     */
    public function trace_log()
    {
        return M('global_log')->where("order_id='" . $this->order_id . "'")->select();
    }

    /**
     * 开始过户，生成过户任务
     * 置拍单状态为“过户中"
     * 保存过户信息和过户备注信息到过户表
     *
     * @param Array $data 过户数据
     *
     * @return   boolean
     */
    public function start_trade($data)
    {
        //数据有效性验证
        $data['order_id'] = $this->order_id;
        if (empty($data['emp_id'])) {
            AuctionException::make_throw('300007');
        }
        if (empty($data['contact'])) { //车商联系人
            AuctionException::make_throw('600004');
        }
        if (empty($data['idcard'])) {//联系人身份证
            AuctionException::make_throw('600005');
        }
        if (empty($data['phone'])) {//联系人电话
            AuctionException::make_throw('600006');
        }
        if (empty($data['company'])) {//过户公司
            AuctionException::make_throw('700004');
        }
        $data['createtime'] = date('Y-m-d H:i:s');
        $c = M('transfer_log')->where("order_id='" . $this->order_id . "'")->find();
        if ($c) {
            AuctionException::make_throw('700020');
        }
        M()->startTrans();
        $res = M('transfer_log')->add($data);
        if ($res) {
            $status_data = array();
            //更改拍单状态
            $status_data['status'] = '10';
            $status_data['last_time'] = date('Y-m-d H:i:s');
            $this->update($status_data);
            M()->commit();
            $log = array('order_id' => $this->order_id, 'emp_id' => $data['emp_id'], 'action' => '确认过户成功');
        } else {
            M()->rollback();
            $res = false;
            $log = array('order_id' => $this->order_id, 'emp_id' => $data['emp_id'], 'action' => '确认过户失败');
        }
        //操作日志
        \AuctionCore\System\SystemLog::add($log);
        return $res;
    }

    /**
     * 置拍单状态为“待付尾款"
     *
     * @param int $emp_id 员工ID
     *
     * @return   boolean
     */
    public function update_status($emp_id)
    {
        //数据有效性验证
        if (empty($emp_id)) {
            AuctionException::make_throw('300007');
        }
        //
        $data = array();
        $data['last_time'] = date('Y-m-d H:i:s');
        $data['status'] = '11';
        $data['pay_type'] = '2';
        $res = $this->update($data);
        //操作日志
        $log = array('order_id' => $this->order_id, 'emp_id' => $emp_id, 'action' => '更改状态为待付尾款');
        \AuctionCore\System\SystemLog::add($log);
        return $res;
    }

    /**
     * 已付首款
     * 更改状态为”待过户",记录备注信息
     *
     * @param    int $emp_id 员工ID
     *
     * @return   boolean
     */
    public function pay_first($emp_id)
    {
        //数据有效性验证
        if (empty($emp_id)) {
            AuctionException::make_throw('300007');
        }

        //
        $data = array();
        $data['last_time'] = date('Y-m-d H:i:s');
        $data['status'] = '9';//9 待过户
        $data['pay_type'] = '1';//1 首款支付 2 尾款支付
        $res = $this->update($data);

        //操作日志
        $log = array('order_id' => $this->order_id, 'emp_id' => $emp_id, 'action' => '确认支付尾款');
        \AuctionCore\System\SystemLog::add($log);
        return $res;

    }

    /**
     * 已付尾款(final_payment)
     * 更改状态为”拍单成功",车源交易成功，记录备注信息
     *
     * @param    Array $data 需更新数据
     *
     * @return   boolean
     */
    public function pay_tail($data)
    {
        $data['order_id'] = $this->order_id;
        if (empty($data['emp_id'])) {
            AuctionException::make_throw('300007');
        }
        $data['pay_type'] = '2';
        $data['createtime'] = date('Y-m-d H:i:s');

        //事务开始
        M()->startTrans();
        $res = M('pay_log')->add($data);

        //修改拍单状态
        $info = array();
        $info['status'] = '13';
        $info['last_time'] = date('Y-m-d H:i:s');
        $res1 = $this->update($info);

        //修改车源状态
        $info = array();
        $info['status'] = '9';
        $info['modify_time'] = date('Y-m-d H:i:s');
        $order = self::detail();
        $car = new \AuctionCore\CarResource\Car($order['car_id']);
        $res2 = $car->update($info);

        //解冻保证金
        $asset = new \AuctionCore\CarDealer\AssetCenter();
        $asset->free($this->order_id);

        //记录操作日志
        $log = array('order_id' => $this->order_id, 'emp_id' => $data['emp_id'], 'action' => '确认支付尾款');
        \AuctionCore\System\SystemLog::add($log);

        if ($res && $res1 && $res2) {
            //事务提交
            M()->commit();
            return true;
        } else {
            M()->rollback();
            \Think\Log::record('确认付尾款时发生回滚事件！order_id:' . $this->order_id . ',emp_id:' . $data['emp_id']);
            return false;
        }
    }

    /**
     * 确认收款
     *
     * @param   array $payer_info 付款人信息
     *                                 [付款人姓名，付款银行，付款时间，付款帐号]
     *
     * @return   boolean
     */
    public function confirm_proceeds($payer_info)
    {
        $payer_info['order_id'] = $this->order_id;
        if (empty($payer_info['emp_id'])) {
            AuctionException::make_throw('300007');
        }
        if (empty($payer_info['payer_name'])) {
            AuctionException::make_throw('700016');
        }
        if (empty($payer_info['pay_bank'])) {
            AuctionException::make_throw('700018');
        }
        if (empty($payer_info['payer_account'])) {
            AuctionException::make_throw('700017');
        }
        if (empty($payer_info['pay_time'])) {
            AuctionException::make_throw('700019');
        }
        $payer_info['createtime'] = date('Y-m-d H:i:s');
        $res = M('proceeds_log')->add($payer_info);

        if ($res) {
            //操作日志
            $log = array('order_id' => $this->order_id, 'emp_id' => $payer_info['emp_id'], 'action' => '确认收款');
            \AuctionCore\System\SystemLog::add($log);
            return true;
        } else {
            \Think\Log::record('确认收款时发生错误，收款失败！order_id:' . $this->order_id . ',emp_id:' . $payer_info['emp_id']);
            return false;
        }
    }

    /**
     * 更新拍单
     *
     * @param array $info 要更新的拍单信息
     * @param array $map 条件
     *
     * @return boolean
     */
    public function update($info, $map = array())
    {
        if (empty($map)) {
            $map['order_id'] = array('eq', $this->order_id);
        }
        $info['last_time'] = date('Y-m-d H:i:s');
        return M('order')->where($map)->save($info);
    }

    /*
     * 拍单参与竞拍车商统计
     * */
    public function stat_bidding_dealer()
    {
        return M('bidding_log')->where("order_id='" . $this->order_id . "'")->getField('count(distinct(dealer_id))');
    }

    /*
     * 拍单参与竞拍车商出价统计
     * */
    public function stat_bidding_price()
    {
        return M('bidding_log')->where("order_id='" . $this->order_id . "'")->count();
    }

    /*
     * 获取拍单出价记录
     * */
    public function get_bidding_price_log($limit = '100')
    {
        return M('bidding_log')->where("order_id='" . $this->order_id . "'")->order("bidding_id desc")->limit("0," . $limit)->select();
    }

    /*
     * 获取投标最高价
     * */
    public function get_bid_max_price()
    {
        return M('bid_log')->where("order_id='" . $this->order_id . "'")->max('price');
    }

    /*
     * 根据order_id 获取car_id,owner_id
     * @return Array
     * */
    public function get_car_owner_id()
    {
        return M('order')->alias('o')->field("c.car_id,c.owner_id")->join(C('DB_PREFIX') . "cars c ON c.car_id=o.car_id")
            ->where("o.order_id='" . $this->order_id . "'")->find();
    }

    /*
     * 重新排序场次内拍单顺序
     * */
    public function reset_order_rank()
    {
        $order = $this->detail();
        $res = M('order')->where("scene_id='" . $order['scene_id'] . "' AND rank>'" . $order['rank'] . "'")->order('rank')->select();
        $rs = array();
        foreach ($res as $val) {
            $data = array();
            $data['rank'] = $val['rank'] - 1;
            $rs[] = M('order')->where("order_id='" . $val['order_id'] . "'")->save($data);
        }
        return !in_array(false, $rs) ? true : false;
    }

    /**
     * @return bool
     */
    public function reset_order_start_time($is_timing_order = false)
    {
        if (!$is_timing_order) {
            $order = $this->detail();
            $res = M('order')->alias('o')->join(C('DB_PREFIX') . "order_scene os on os.scene_id=o.scene_id")
                ->where("os.scene_id='" . $order['scene_id'] . "' AND o.rank>='" . $order['rank'] . "' and o.is_timing_order=0")
                ->order('o.rank')->select();
            $rs = array();
            foreach ($res as $val) {
                $data = array();
                $data['bidding_start_time'] = date("Y-m-d H:i:s", strtotime($val['bidding_start_time']) - $order['est_elapsed_time']);
                $rs[] = M('order')->where("order_id='" . $val['order_id'] . "'")->save($data);
            }
            return !in_array(false, $rs) ? true : false;
        }
        return true;
    }

    /*
     * 获取下一个拍品
     * @param int $scene_id 场次ID
     * @return Array
     * */
    public function get_next()
    {
        $order = $this->detail();
        $cond = "o.scene_id='" . $order['scene_id'] . "' AND bidding_start_time>'" . $order['bidding_start_time'] . "'";//301 为拍单状态 等待竞标
        $res = M('order')->alias('o')->field("o.order_id,o.order_no,o.status,c.car_cc,c.turbo,c.gearbox,c.brand_id,c.series_id,c.model_id")
            ->join(C('DB_PREFIX') . "cars c ON o.car_id=c.car_id")
            ->order("bidding_start_time")
            ->where($cond)->find();
        return $res;
    }

    /*
     *今明拍品统计
     * */
    public static function stat_bid($date)
    {
        $cond = "o.status in(3,301,4) AND os.status in(1,2) AND os.starttime like '" . $date . "%'";
        return M('order')->alias('o')->join(C('DB_PREFIX') . "order_scene os ON os.scene_id=o.scene_id")
            ->where($cond)->count();
    }

    /*
     * 出价(投标出价/竞价出价)
     * @param $tbl
     * @param $column
     * @return Array
     * */
    public function get_all_price()
    {
        /*
                 $arr = array();
                //竞标前20名
                $bidding = M('bidding_log')->field("dealer_id,max(after_price) after_price")
                    ->where("order_id='" . $this->order_id . "'")->group("dealer_id")->order("after_price DESC")->limit('0,20')->select();
                foreach ($bidding as $v) {
                    $arr[intval($v['after_price'])] = array('price' => $v['after_price'], 'type' => 'bidding', 'dealer_id' => $v['dealer_id']);
                }
                //投标前20名
                $sql = "SELECT price,dealer_id FROM au_bid_log a INNER JOIN (SELECT MAX(bid_id) bid_id FROM au_bid_log WHERE order_id='" . $this->order_id . "'
                                GROUP BY dealer_id) b ON a.`bid_id` = b.bid_id ORDER BY price DESC,a.bid_id DESC LIMIT 0,20";

                $bid = M()->query($sql); dump($bid);
                foreach ($bid as $value) {//
                    $arr[intval($value['price'])] = array('price' => $value['price'], 'type' => 'bid', 'dealer_id' => $value['dealer_id']);
                }
                krsort($arr);
        */
        $sql = "SELECT * FROM (
                SELECT * FROM
                (
                    SELECT `order_id`,`dealer_id`,`price`,`createtime` ,'bid' bidtype FROM au_bid_log a INNER JOIN (SELECT MAX(bid_id) bid_id FROM au_bid_log WHERE order_id='" . $this->order_id . "' GROUP BY dealer_id) b ON a.`bid_id` = b.bid_id
                    UNION
                    SELECT  `order_id`,`dealer_id`,`after_price` `price`,`createtime`,'bidding' bidtype FROM `au_bidding_log` WHERE `order_id` IN (SELECT `order_id` FROM `au_order` WHERE order_id='" . $this->order_id . "')
                 ) a ORDER BY order_id,price DESC,createtime DESC
        ) b GROUP BY order_id,dealer_id ORDER BY order_id,price DESC LIMIT 0,20";
        $arr = M()->query($sql);
        return array_slice($arr, 0, 20);
    }

    /*
     *获取拍单、车源、车主信息
     * @param int 获得此单追踪权的客户
     * */
    public function owner_confirm_detail()
    {

        $cols = "o.order_id,o.order_no,o.car_id,o.bid_best_price,o.bidding_best_price,o.bidding_end_time,o.bidding_start_time,o.act_elapsed_time,o.first_pay_status,
            o.is_consult,o.company_subsidies,o.success_price,o.status,o.owner_confirm_service_id,o.fail_type,o.first_money,o.tail_money,o.is_self_confirm,
            o.reserve_price,co.owner_id,co.uid,co.seller_name,co.phone,co.owner_type,co.contact_person,o.depreciate,c.brand_id,c.series_id,c.model_id,c.car_source,
            c.plate_prefix,c.plate_suffix,c.car_color,composite_state,accident_level,c.car_status,c.posttime,c.transfer_limit,
            c.car_no,c.emission,c.first_reg_date,c.pointer_mileage,c.reg_city,c.vin,c.is_valid,
            pl.pay_type,pl.fid,pl.bank_account";
        $res = M('order')->alias('o')->field($cols)
            ->join(C('DB_PREFIX') . "cars as c ON c.car_id=o.car_id")
            ->join(C('DB_PREFIX') . "car_owner as co ON co.owner_id=c.owner_id")
            ->join("LEFT JOIN " . C('DB_PREFIX') . "pay_log as pl ON pl.car_id = o.car_id AND pl.pay_type = 1")
            ->where("o.order_id='" . $this->order_id . "'")->find();
//        echo M()->getLastSql();
        $cm = new \AuctionCore\CarResource\CarModel();
        $brand = $cm->get_model_by_id($res['brand_id'], 'brand');
        $series = $cm->get_model_by_id($res['series_id'], 'series');
        $model = $cm->get_model_by_id($res['model_id']);
        $res['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
        $res['format_reserve_price'] = format_money($res['reserve_price']);
        $res['format_best_price'] = format_money($res['bidding_best_price'] > $res['bid_best_price'] ? $res['bidding_best_price'] : $res['bid_best_price']);
        $res['best_price'] = $res['bidding_best_price'] > $res['bid_best_price'] ? $res['bidding_best_price'] : $res['bid_best_price'];
        $res['car_color'] = C('CAR_COLOR.' . $res['car_color']);
        $res['emission'] = C('INT_EMISSION_STD.' . $res['emission']);
        $res['plate_prefix'] = C('PLATE_PREFIX.' . $res['plate_prefix']);
        $res['pointer_mileage'] = formatMileage($res['pointer_mileage']);
        if ($res['car_source'] == 1 && !empty($res['bank_account'])) {
            $bank_account = json_decode($res['bank_account'], true);
            $res['bank_name'] = $bank_account['bank_name'];
            $res['card_no'] = $bank_account['card_no'];
            $res['account_name'] = $bank_account['account_name'];
        }
        $res['owner_type_name'] = C('OWNER_TYPE_NAME')[$res['owner_type']];
        return $res;
    }

    /*
     * 获取客服对车主确认的跟踪日志
     * */
    public function get_owner_confirm_trace_log()
    {
        $res = M('owner_confirm_log')->alias('ocl')->field('ocl.*,e.real_name')
            ->join(C('DB_PREFIX') . "employee e ON e.emp_id=ocl.service_id")
            ->where("ocl.order_id='" . $this->order_id . "'")->select();
        return $res;
    }

    /**
     *  获取拍单、车源、车主信息
     *
     * @param int $dealer_id2 第二名车商ID
     * */
    public function dealer_confirm_detail($status = 0)
    {
        /*
        if ($dealer_id2) {//第一名已违约，查询第二名车商
            $cols = "o.order_id,o.order_no,o.bidding_best_price,o.bid_best_price,o.bidding_start_time,o.act_elapsed_time
                        ,o.reserve_price,o.success_price,o.status,o.bidding_better_dealer_id,o.dealer_confirm_status,o.is_consult
                        ,c.plate_prefix,c.plate_suffix,c.car_color,composite_state,accident_level,c.car_status,c.posttime
                        ,c.car_no,c.emission,c.first_reg_date,c.pointer_mileage,c.reg_city,c.vin";
            //c.car_no,c.emission,c.first_reg_date,c.pointer_mileage,c.reg_city,c.vin
            $res = M('order')->alias('o')->field($cols)
                ->join(C('DB_PREFIX') . "cars as c ON c.car_id=o.car_id")
                ->where("o.order_id='" . $this->order_id . "'")->find();
            //第二名车商信息
            $res1 = M('car_dealer')->field("fullname,level,contact_person,contact_mobile")
                ->where("dealer_id='" . $dealer_id2 . "'")->find();
            //找出第二名车商的最高出价
            $bid_price = M('bid_log')->where("dealer_id='" . $dealer_id2 . "' AND order_id='" . $this->order_id . "'")
                ->order("createtime desc")->getField('price');
            $bidding_price = M('bidding_log')->where("dealer_id='" . $dealer_id2 . "' AND order_id='" . $this->order_id . "'")
                ->order("createtime desc")->getField('after_price');
            $res['trade_price'] = $bidding_price > $bid_price ? $bidding_price : $bid_price;

            $res = array_merge($res, $res1);
        } else {//第一名车商详情
        */
        //目前不找第二名了
        $cols = "o.order_id,o.order_no,o.bidding_best_price,o.bid_best_price,o.bidding_start_time,o.act_elapsed_time
                 ,o.reserve_price,o.success_price,o.status,o.bidding_better_dealer_id,o.dealer_confirm_status,o.is_consult
                 ,c.car_id,c.plate_prefix,c.plate_suffix,c.car_color,composite_state,accident_level,c.car_status,c.posttime
                 ,c.car_no,c.emission,c.first_reg_date,c.pointer_mileage,c.reg_city,c.vin,c.brand_id,c.series_id,c.model_id
                 ,cd.dealer_id,cd.fullname,cd.level,cd.contact_person,cd.contact_mobile
                 ,ada.dealer_id,ada.trade_price";
        $res = M('order')->alias('o')->field($cols)
            ->join(C('DB_PREFIX') . "cars as c ON c.car_id=o.car_id")
            ->join(C('DB_PREFIX') . "dealer_auctioned as ada ON ada.order_id=o.order_id AND ada.status=$status")
            ->join(C('DB_PREFIX') . "car_dealer as cd ON cd.dealer_id=ada.dealer_id")
            ->where("o.order_id='" . $this->order_id . "'")->find();
        //}
        //echo M()->getLastSql();
        if (empty($res)) {
            return array();
        }
        $cm = new \AuctionCore\CarResource\CarModel();
        $brand = $cm->get_model_by_id($res['brand_id'], 'brand');
        $series = $cm->get_model_by_id($res['series_id'], 'series');
        $model = $cm->get_model_by_id($res['model_id']);
        $res['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
        $res['bidding_end_time'] = date('Y-m-d H:i:s', (strtotime($res['bidding_start_time']) + $res['act_elapsed_time']));
        $res['level'] = C('DEALER_LEVEL.' . $res['level']);
        $res['format_reserve_price'] = format_money($res['reserve_price']);
        $res['success_price'] = format_money($res['success_price']);
        $res['car_color'] = C('CAR_COLOR.' . $res['car_color']);
        $res['emission'] = C('INT_EMISSION_STD.' . $res['emission']);
        $res['plate_prefix'] = C('PLATE_PREFIX.' . $res['plate_prefix']);
        $res['pointer_mileage'] = round($res['pointer_mileage'] / 10000, 2);
        //流拍过来的车辆,取拍卖最高价
        if ($res['is_consult'] == 1) {
            $res['best_price'] = $res['bidding_best_price'] > $res['bid_best_price'] ? format_money($res['bidding_best_price']) : format_money($res['bid_best_price']);
            $res['consult_price'] = format_money($res['trade_price']);
        } else {
            $res['best_price'] = format_money($res['trade_price']);
        }
        return $res;
    }


    /*
 *获取拍单、车源、车主信息
 * @param int 获得此单追踪权的客户
 * */
    public function platform_confirm_detail()
    {
        $map['o.order_id'] = ['eq', $this->order_id];
        $cols = "o.order_id,o.order_no,o.car_id,o.bid_best_price,o.bidding_best_price,o.bidding_end_time,o.bidding_start_time,
            o.act_elapsed_time,o.first_pay_status,o.is_consult,o.company_subsidies,o.success_price,o.status,o.transfer_fee,
            o.platform_confirm_service_id,o.platform_confirm_increase,o.confirm_type,o.success_dealer_id,o.scene_id,
            o.fail_type,o.first_money,o.tail_money,o.is_self_confirm,c.brand_id,c.series_id,c.model_id,o.reserve_price,o.depreciate,
            c.plate_prefix,c.plate_suffix,c.car_color,composite_state,accident_level,c.car_status,c.posttime,c.transfer_limit,c.au_times,
            c.sid,c.car_no,c.emission,c.first_reg_date,c.pointer_mileage,c.reg_city,c.location_area,c.vin,c.is_valid,c.re_auction_type,
            c.suggest_min_price,c.suggest_max_price,c.self_receive_dealer_id,c.self_receive_price,c.is_dealer_breach,c.is_self_receive,
            co.owner_id,co.uid,co.comefrom,co.comefrom_url,co.seller_name,co.phone";
        $res = M('order')->alias('o')->field($cols)
            ->join(C('DB_PREFIX') . "cars as c ON c.car_id=o.car_id")
            ->join(C('DB_PREFIX') . "car_owner as co ON co.owner_id=c.owner_id")
            ->where($map)->find();
        //echo M()->getLastSql();
        $cm = new CarModel();
        $Addr = new Address();
        $brand = $cm->get_model_by_id($res['brand_id'], 'brand');
        $series = $cm->get_model_by_id($res['series_id'], 'series');
        $model = $cm->get_model_by_id($res['model_id']);
        $res['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
        $res['format_reserve_price'] = format_money($res['reserve_price']);
        $res['format_best_price'] = format_money($res['bidding_best_price'] > $res['bid_best_price'] ? $res['bidding_best_price'] : $res['bid_best_price']);
        $res['best_price'] = $res['bidding_best_price'] > $res['bid_best_price'] ? $res['bidding_best_price'] : $res['bid_best_price'];
        $res['car_color'] = C('CAR_COLOR.' . $res['car_color']);
        $res['emission'] = C('INT_EMISSION_STD.' . $res['emission']);
        $res['plate_prefix'] = C('PLATE_PREFIX.' . $res['plate_prefix']);
        $res['pointer_mileage'] = formatMileage($res['pointer_mileage']);
        $res['reg_city'] = $Addr->get_name_by_code($res['reg_city']);
        $res['location_area'] = $Addr->get_name_by_code($res['location_area']);
        $res['transfer_limit'] = C('TRANSFER_LIMIT')[$res['transfer_limit']];

        //出价排名
        $rank_data = $this->get_order_biding_rank($res['order_id']);
        $res['rank_data'] = array_slice($rank_data, 0, 3);
        $reserve_price_format = format_money($res['reserve_price']);
        $res['reserve_price_count'] = $res['reserve_price'];
        $res['reserve_price'] = $reserve_price_format;

        $bidding_best_price = $res['bidding_best_price'] > $res['bid_best_price'] ? $res['bidding_best_price'] : $res['bid_best_price'];
        $res['bidding_best_price'] = format_money($bidding_best_price);
        $res['bidding_best_price_count'] = sprintf('%.2f', ($bidding_best_price - $res['consult_increase']));
        $res['suggest_price'] = $res['suggest_min_price'] . '元' . ' - ' . $res['suggest_max_price'] . '元';
        $res['owner_success_price'] = $res['success_price'] + $res['company_subsidies'];
        $res['pay_commision'] = get_commision($res['success_price']);
        $res['dealer_success_price'] = $res['success_price'] + $res['pay_commision'] + $res['transfer_fee'];

        if ($res['is_dealer_breach'] == 1) {
            //仲裁人
            $arbitrator_info = $this->getArbitratorBySid($res['sid']);
            $res['issue_done_emp'] = $arbitrator_info['real_name'];
            $res['issue_done_phone'] = $arbitrator_info['mobile'];
        }
        //自收价格
        if ($res['is_self_receive'] == 1) {
            $carIds = Car::getAllCarIdBySid($res['sid']);
            $where = [
                'car_id' => ['in', $carIds]
            ];
            $self_receive_data = M('self_receive_car')->where($where)->order('src_id ASC')->limit(1)->find();
            //自收人
            $dealer = new Dealer($res['self_receive_dealer_id']);
            $dealer_info = $dealer->detail();
            if(!empty($dealer_info)){
                $d = new Dealer();
                $dealer_info = $d->get_contact_mobile_byAntNestfind($dealer_info);
            }
            $res['dealer_contact_person'] = $dealer_info['contact_person'];
            $res['dealer_contact_mobile'] = $dealer_info['contact_mobile'];
            //自收价格
            $AuOrder = new AuOrder($self_receive_data['order_id']);
            $self_receive_order = $AuOrder->detail();
            $res['self_receive_price'] = $self_receive_order['success_price'];
        }
        return $res;
    }

    /**
     * 根据车辆sid获取最近的仲裁操作人
     * @param $sid
     * @return array|bool
     */
    private function getArbitratorBySid($sid)
    {
        $purchaseOrderObj = new PurchaseOrder();
        $purchaseOrderData = $purchaseOrderObj->viewBySid($sid);
        $changeOrderData = ChangeOrder::getLatestChangeOrderByPurchaseOrderId($purchaseOrderData['id']);
        $arbitrator_info = ChangeOrder::getOperatorByMidSAndAction($changeOrderData['mid'], 2);
        return $arbitrator_info;
    }

    /*
     * 获取客服对平台确认的跟踪日志
     **/
    public function add_platform_confirm_trace_log($data)
    {
        if (empty($data)) {
            return false;
        }
        return M('platform_confirm_log')->add($data);
    }

    /*
     * 获取客服对平台确认的跟踪日志
     * @params array $map
     * @return array
     **/
    public function get_platform_confirm_trace_log($map = [])
    {
        $map['pcl.order_id'] = ['eq', $this->order_id];
        $order = 'pcl.createtime desc';
        $res = M('platform_confirm_log')->alias('pcl')->field('pcl.*,e.real_name')
            ->join(C('DB_PREFIX') . "employee e ON e.emp_id = pcl.emp_id")
            ->where($map)
            ->order($order)
            ->select();
        return $res;
    }

    /**
     * 获取平台确认日志单条
     *
     * @param $map
     *
     */
    public function get_platform_confirm_log($map = [])
    {
        $map['pcl.order_id'] = ['eq', $this->order_id];
        $order = 'pcl.createtime desc';
        $res = M('platform_confirm_log')->alias('pcl')->field('pcl.*,e.real_name')
            ->join(C('DB_PREFIX') . "employee e ON e.emp_id = pcl.emp_id")
            ->where($map)
            ->order($order)
            ->find();
        return $res;
    }


    /*
     * 获取客服对车商确认的跟踪日志
     * */
    public function get_dealer_confirm_trace_log()
    {
        $res = M('dealer_confirm_log')->alias('dcl')->field('dcl.*,e.real_name')
            ->join(C('DB_PREFIX') . "employee e ON e.emp_id=dcl.service_id")
            ->where("dcl.order_id='" . $this->order_id . "'")->select();
        return $res;
    }

    /**
     * 获取客服对车主确认的跟踪日志
     */
    public function get_trace_log($table = '')
    {
        if (!$table) {
            return false;
        }
        $res = M($table)->alias('l')->field('l.*,e.real_name')
            ->join(C('DB_PREFIX') . "employee e ON e.emp_id = l.service_id")
            ->where("l.order_id='" . $this->order_id . "'")->select();
        return $res;
    }

    /*
    * 获取某个表的数据
    * */
    public function get_every_trace_log($table = '')
    {
        if (!$table) {
            return false;
        }
        $res = M($table)->where("order_id='" . $this->order_id . "'")->select();
        return $res;
    }


    /**
     * @param int $result (1同意卖车 2跟踪确认 3不卖 4磋商成交 5重拍)
     *
     * @return mixed
     */
    public function get_owner_confirm_log($result = 0)
    {
        $map = ['l.order_id' => $this->order_id];
        if ($result > 0) {
            $map['l.result'] = $result;
        }
        return M('owner_confirm_log')->alias('l')->field('l.createtime as confirm_success_time,e.*')
            ->join(C('DB_PREFIX') . "employee e ON e.emp_id=l.service_id")
            ->where($map)->select();
    }

    /**
     * 根据owner_id获取确认日志
     *
     * @param int $owner_id
     * @param int $result
     */
    public function get_owner_confirm_log_by_owner_id($owner_id, $result = 0)
    {
        $map['l.owner_id'] = $owner_id;
        if ($result > 0) {
            $map['l.result'] = $result;
        }
        return M('owner_confirm_log')->alias('l')->field('l.createtime as confirm_success_time,e.*')
            ->join(C('DB_PREFIX') . "employee e ON e.emp_id=l.service_id")
            ->where($map)->find();
    }

    /**
     * 找出第一名车商
     */
    public function get_bidding_best_dealer_id()
    {
        return M('dealer_auctioned')->where("order_id='" . $this->order_id . "' AND status <>1")->getField('dealer_id');
    }

    /**
     * 找出第二名车商
     */
    public function get_bidding_better_dealer_id()
    {
        $arr = $this->get_all_price();
        return $arr[1]['dealer_id'];
    }

    /**
     * 流拍跟踪记录
     *
     * @param array $data 数据
     *
     * @boolean
     */
    public function unsold_trace_log($data = array())
    {
        if (empty($data['order_id'])) {
            AuctionException::make_throw('700027');
        }

        if (empty($data['owner_id'])) {
            AuctionException::make_throw('400004');
        }

        $data['createtime'] = date('Y-m-d H:i:s');
        return M('unsold_confirm_log')->add($data);
    }

    /**
     * 设置跟踪日志
     *
     * @param string $table
     * @param array $data
     *
     * @return boolean|\Think\mixed
     */
    public function set_trace_log($table, $data)
    {
        if (empty($data['order_id'])) {
            $data['order_id'] = $this->order_id;
        }
        $data['createtime'] = date('Y-m-d H:i:s');
        return M($table)->add($data);
    }

    public function update_trace_log($table, $data)
    {
        $map = array();
        $map['order_id'] = $this->order_id;
        return M($table)->where($map)->save($data);
    }

    public function obtain_trace_log($table)
    {
        $map = array();
        $map['order_id'] = $this->order_id;
        return M($table)->where($map)->find();
    }


    /**
     * 更新过户跟踪日志
     */
    public function update_transfer_log($data)
    {
        $map = array();
        $map['result'] = 1;
        $map['order_id'] = $data['order_id'];
        $update_data = array(
            'emp_id' => $data['emp_id'],
            'remark' => $data['remark'],
            'result' => $data['result'],
            'createtime' => date('Y-m-d h:i:s')
        );
        return M('transfer_log')->where($map)->save($update_data);
    }

    //获取代付收款信息
    public function get_pay_trace_log($car_id)
    {
        $map = array();
        $map['pay_type'] = array('eq', 1);
        $map['car_id'] = array('eq', $car_id);
        return M('pay_log')->where($map)->find();
    }

    /**
     * 获取过户日志
     *
     * @return unknown
     */
    public function get_transfer_log($result = '')
    {
        $where = "tl.order_id='" . $this->order_id . "'";
        if (!empty($result)) {
            $where .= " AND tl.result=' " . $result . "'";
        }
        $res = M('transfer_log')->alias('tl')->field('tl.*,e.real_name')
            ->join(C('DB_PREFIX') . "employee e ON e.emp_id=tl.emp_id")
            ->where($where)->find();
        // M()->getLastSql();
        return $res;
    }

    /**
     * 获取付款日志
     *
     * @Author   Eric
     * @date     2016/1/28 15:44
     * @pay_type 1首付支付 , 2尾款支付
     * @return Array
     */
    public function get_pay_log($pay_type = '1')
    {
        $where = "tl.order_id='" . $this->order_id . "'";
        if (!empty($result)) {
            $where .= " AND tl.pay_type=' " . $result . "'";
        }
        $res = M('pay_log')->alias('tl')->field('tl.*,e.real_name')
            ->join(C('DB_PREFIX') . "employee e ON e.emp_id=tl.emp_id")
            ->where($where)->find();
        return $res;
    }

    /**
     * 获取签约日志
     *
     * @param array $params
     *
     * @return array $sign_info
     */
    public static function get_signature_log($params = array())
    {
        $map = array();

        if (!empty($params['result'])) {
            $map['asl.result'] = $params['result'];
        }
        if (!empty($params['owner_id'])) {
            $map['asl.owner_id'] = $params['owner_id'];
        }
        $res = M('signature_log')->alias('asl')->field('asl.*,apl.pay_type,e.real_name as deliver,e.mobile as deliver_mobile')
            ->join("left join " . C('DB_PREFIX') . "pay_log apl ON asl.order_id = apl.order_id")
            ->join(C('DB_PREFIX') . "employee e ON e.emp_id=asl.emp_id")
            ->order("apl.pay_id DESC")
            ->where($map)->find();
        //echo M()->getLastSql();
        return $res;
    }

    /*
     *根据当前拍单scene_id,rank 找出开拍时间(为等待竞标的拍单)
     * @param int $scene_id 场次
     * @param int $rank 排序
     * */
    public function get_time_offset($scene_id)
    {
        $map1 = array();
        $map1['os.scene_id'] = array('eq', $scene_id);
        $map1['o.is_timing_order'] = array('eq', '0');//排除定时单
        $resp = M('order')->alias('o')->field('os.scene_id,o.order_id,o.rank,o.act_elapsed_time,o.est_elapsed_time,o.bidding_start_time')->join(C('DB_PREFIX') . "cars c On o.car_id=c.car_id")
            ->join(C('DB_PREFIX') . "order_scene os On os.scene_id=o.scene_id")->where($map1)->order("find_in_set(o.status,'4,301,3'),os.starttime,o.rank")->select();
        $time_diff = 0;
        $arrTimeDiff = array();
        foreach ($resp as $val) {
            $time_diff += ($val['act_elapsed_time'] > $val['est_elapsed_time'] ? $val['act_elapsed_time'] : $val['est_elapsed_time']);
            $arrTimeDiff[$val['scene_id']][] = array('order_id' => $val['order_id'], 'diff' => $time_diff + 5);
        }
        foreach ($arrTimeDiff[$scene_id] as $idx => $v) {
            if ($this->order_id == $v['order_id']) {
                $time_offset = $arrTimeDiff[$scene_id][$idx - 1]['diff'];
                break;
            }
        }

        return $time_offset;
    }

    /**
     * 记录第二名拍到的车
     *
     * @param int $dealer_id 车商ID
     * @param int $dealer_id2 车商ID
     * @param double $price 第二名车商竞标最高价
     */
    public function dealer2_auctioned($dealer_id, $dealer_id2)
    {
        M()->startTrans();
        //插入第二名记录
        $data = array();
        $data['dealer_id'] = $dealer_id2;
        $data['order_id'] = $this->order_id;
        $data['createtime'] = date('Y-m-d H:i:s');
        $bid_price = M('bid_log')->where("dealer_id='" . $dealer_id2 . "' AND order_id='" . $this->order_id . "'")
            ->order("createtime desc")->getField('price');
        $bidding_price = M('bidding_log')->where("dealer_id='" . $dealer_id2 . "' AND order_id='" . $this->order_id . "'")
            ->order("createtime desc")->getField('after_price');
        $data['trade_price'] = $bidding_price > $bid_price ? $bidding_price : $bid_price;
        $res = M('dealer_auctioned')->add($data);
        //更新第一名记录为无效
        $data = array();
        $data['status'] = '1';
        $res1 = M('dealer_auctioned')->where("order_id='" . $this->order_id . "' AND dealer_id='" . $dealer_id . "'")->save($data);
        if ($res && $res1) {
            M()->commit();
            return true;
        } else {
            M()->rollback();
            \Think\Log::record('插入第二名到买到的车表失败，事务回滚！');
            return false;
        }
    }

    /**
     * 通过拍单获取车商id
     *
     * @param int $order_id
     *
     * @return boolean|number|\Think\mixed
     */
    public function get_uid_by_order()
    {
        $map = array(
            'da.order_id' => $this->order_id,
            'da.status' => 0
        );
        $prefix = C('DB_PREFIX');
        $uid = M('dealer_auctioned')->alias("da")->field('du.uid')
            ->join($prefix . "dealer_user as du on da.dealer_id=du.dealer_id")
            ->where($map)->find();
        if (empty($uid)) {
            return 0;
        }
        return $uid['uid'];
    }

    /**
     * 添加拍单跟踪信息
     */
    /* public static function add_order_trace_log($order_action_data)
     {
         $order_trace = M('order_trace_log');
         $createtime = date("Y-m-d H:i:s", time());
         $order_trace_log['order_id'] = $order_action_data['order_id'];
         $order_trace_log['car_id'] = $order_action_data['car_id'];
         $order_trace_log['action_log'] = $createtime . "/t" . $order_action_data['order_trace_msg'] . '/t' . $order_action_data['employee'] . '/n/t';
         $order_trace_log['createtime'] = $createtime;
         $ok = $order_trace->add($order_trace_log);
         return $ok;
     }*/

    /**
     * 拍单状态跟踪日志
     *
     * @param $order_id
     *
     * @return array
     */
    /*    public static function get_order_trace_log($order_id)
        {
            if($order_id < 1){
                return false;
            }
            $order_trace_log = M('order_trace_log')->field('action_log')->where(array('order_id' => $order_id))->find();
            $action_log = $order_trace_log['action_log'];
            $action_log_arr = array_filter(explode("/n/t", $action_log));
            $order_action_log = array();
            foreach ($action_log_arr as $k => $v) {
                $order_action_log[$k] = explode('/t', $v);
            }
            $order_action_log = $this->bid_history_sort($order_action_log, '0');
            return $order_action_log;
        }*/

    /**
     * 添加拍单跟踪信息
     *
     * @param int $order_id
     * @param array $order_action_data
     *
     * @return int
     */
    public static function add_order_trace_log($order_id, $order_action_data)
    {
        $order_trace = M('order_trace_log_list');
        $order_trace_log['order_id'] = $order_id;
        $car_id = M('order')->where(['order_id' => $order_id])->getField('car_id');
        $order_trace_log['car_id'] = $car_id;
        $emp_id = $order_action_data['emp_id'];
        $employee = \AuctionCore\Account\Back\Employee::user_info_id($emp_id);
        if (!empty($employee)) {
            $emp_name = $employee['real_name'];
        } else {
            $emp_name = '--';
        }
        $order_trace_log['emp_id'] = $emp_id;
        $order_trace_log['emp_name'] = $emp_name;
        $order_trace_log['action_no'] = array_keys(C('ORDER_ACTION_NAME'), $order_action_data['action_name'])[0];
        $order_trace_log['action_name'] = $order_action_data['action_name'];
        $order_trace_log['createtime'] = microtime_time();
        $ok = $order_trace->add($order_trace_log);
        return $ok;
    }

    /**
     * 获取拍单日志跟踪列表
     *
     * @param $order_id
     */
    public static function get_order_trace_log_list($order_id)
    {
        if ($order_id < 1) {
            return false;
        }
        $order_trace = M('order_trace_log_list');
        $cols = 'emp_name,action_name,createtime';
        $list = $order_trace->field($cols)->where(['order_id' => $order_id])->order('id DESC')->select();
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $list[$k]['createtime'] = date('Y-m-d H:i:s', ceil($v['createtime'] / 1000));
                if (empty($v['emp_name'])) {
                    $list[$k]['emp_name'] = '--';
                }
            }
        }
        return $list;
    }

    /**
     * 添加更新拍单跟踪信息
     *
     * @params
     */
    public static function save_order_trace_log($order_id, $order_action_data)
    {
        $order_trace = M('order_trace_log');
        $action_log = $order_action_data['createtime'] . "/t" . $order_action_data['order_trace_msg'] . '/t' . $order_action_data['employee'] . '/n/t';
        $order_trace_log['action_log'] = array('exp', "CONCAT(`action_log`,'$action_log')");
        $ok = $order_trace->where(array('order_id' => $order_id))->save($order_trace_log);
        return $ok;
    }


    /**
     * 获取拍品跟踪日志
     *
     * @param int $order_id
     *
     * @return bool|mixed
     */
    public static function get_order_trace_log($order_id)
    {
        if ($order_id < 1) return false;
        $condition['order_id'] = ['eq', $order_id];
        $cols = 'id,emp_name,action_name,creatime';
        $order = 'id DESC';
        return M("order_trace_log_list")->field($cols)->where($condition)->order($order)->select();
    }


    /**
     * 添加过户跟踪日志
     * @params $order_id
     *
     * @param $params
     */
    public static function save_order_trace_follow_log($order_id, $params)
    {
        $order_trace = M('transfer_follow_log');
        $ok = $order_trace->add($params);
        return $ok;
    }

    /**
     * 添加车商付款跟踪日志
     *
     * @params
     */
    public static function save_dealer_pay_follow_log($params)
    {
        $order_trace = M('dealer_pay_follow_log');
        $ok = $order_trace->add($params);
        return $ok;
    }

    /**
     * 获取车商付款跟踪日志
     *
     * @params
     */
    public static function get_dealer_pay_follow_log($order_id)
    {
        $order_trace = M('dealer_pay_follow_log');
        $prefix = C('DB_PREFIX');
        $res = $order_trace->alias('fg')->field("fg.*,em.real_name")
            ->join('LEFT JOIN ' . $prefix . "employee as em ON em.emp_id=fg.emp_id")
            ->where('fg.order_id=' . $order_id)->select();
        return $res;
    }

    /**
     * 添加车主确认的拍单重拍记录
     */
    public static function add_owner_remake_log($owner_remake_log)
    {
        return M('owner_remake_log')->add($owner_remake_log);
    }

    /**
     * 获取车主确认的拍单重拍记录
     */
    public static function get_owner_remake_log($order_id)
    {
        if (!$order_id) {
            return false;
        }
        $condition['order_id'] = $order_id;
        return M('owner_remake_log')->where($condition)->find();
    }

    /**
     * 根据车源ID，查询拍单信息
     * */
    public static function get_order_by_car_id($car_id)
    {
        return M('order')->where("car_id='" . $car_id . "'")->order("order_id DESC")->find();
    }

    /**
     * 根据车源ID，查询曾经签过约的拍单信息
     */
    public static function get_success_order_by_car_id($car_id)
    {
        //根据car_id 找到所有的拍单，
        //如果拍单状态都为流拍，则返回最后一次的拍单ID
        //如果拍单中有一次签过约，刚返回签过约的拍单ID
        $sql = "SELECT o.order_id,o.status,o.fail_type FROM " . C('DB_PREFIX') . "order o
                    INNER JOIN " . C('DB_PREFIX') . "cars c ON c.car_id=o.car_id
                        WHERE c.car_id='" . $car_id . "' AND (o.status >='5' OR (o.status='12' AND o.fail_type in('4')))";
        $res = M()->query($sql);
        foreach ($res as $value) {
            if (in_array($value['fail_type'], array('4'))) {//拍单曾经签过约
                return $value['order_id'];
            }
        }
        return $value['order_id'];
    }

    /**
     * 获取指定车源与车主签过约的拍单（跟拍单结果无关）
     *
     * @param $car_id
     *
     * @return mixed
     */
    public static function get_signed_order($car_id)
    {
        return M('order')->where("car_id='" . $car_id . "' AND status>=8")->order("order_id DESC")->select();
    }

    /**
     *找到对应拍单对应车辆所在地
     */
    public function get_car_area()
    {
        return M('order')->alias('o')->field('c.location_area')
            ->join(C('DB_PREFIX') . "cars as c ON c.car_id=o.car_id")
            ->where("o.order_id='" . $this->order_id . "'")->find();
    }

    /**
     * 新增车商验车
     * 拍单ID,车商ID,创建时间
     *
     * @return mixed
     */
    public function add_car_dealer_check()
    {
        /*添加车商验车记录*/
        $data = [];
        $data['order_id'] = $this->order_id;
        $dealer = $this->get_dealer_info();
        $data['dealer_id'] = $dealer['dealer_id'];
        $data['createtime'] = date("Y-m-d H:i:s");
        $data['check_limit_time'] = date("Y-m-d H:i:s", strtotime("+1 day"));
        $resCarDealerCheck = M('car_dealer_check')->add($data);
        /*回填拍单表验车状态*/
        $o = new  AuOrder($this->order_id);
        $resOrder = $o->update(array('check_car_status' => 1)); // 待验车
        if ($resCarDealerCheck !== false && $resOrder !== false) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取回车详情
     *
     * @return bool
     */
    public function get_return_detail()
    {
        if ($this->order_id < 1) return false;
        $prefix = C('db_prefix');
        $cols = "o.order_id,o.order_no,o.status,o.bidding_end_time,o.bidding_best_price,o.bid_best_price,o.reserve_price,o.is_consult,
                o.return_check_status,o.company_subsidies,o.first_pay_status,o.success_dealer_id,o.success_price,
               c.car_id,c.sid,c.brand_id,c.series_id,c.model_id,c.car_color,c.emission,c.plate_prefix,c.pointer_mileage,
               c.first_money,c.tail_money,c.car_source,c.three_in_one,c.pay_status,
               c.plate_prefix,c.plate_suffix,c.car_color,c.composite_state,c.accident_level,c.car_status,c.posttime,c.car_source,
               c.car_no,c.emission,c.first_reg_date,c.pointer_mileage,c.reg_city,c.vin,c.transfer_limit,c.owner_id,
               co.seller_name,co.phone as seller_phone,co.owner_type,co.contact_person,co.comefrom,co.comefrom_url,co.first_reg_city,c.location_area,
               e.real_name as checker_name,e.mobile as checker_phone,co.sign_reserve_store,co.sign_service_method";
        $detail = M("order")->alias('o')->field($cols)
            ->join($prefix . "cars as c ON c.car_id=o.car_id")
            ->join($prefix . "car_owner as co ON c.owner_id=co.owner_id")
            ->join($prefix . "employee as e ON e.emp_id=co.checker_id")
            ->where('o.order_id=' . $this->order_id)->find();
//        echo M()->getLastSql();
        $cm = new CarModel();
        $brand = $cm->get_model_by_id($detail['brand_id'], 'brand');
        $series = $cm->get_model_by_id($detail['series_id'], 'series');
        $model = $cm->get_model_by_id($detail['model_id']);
        $detail['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
        $detail['car_color'] = C('CAR_COLOR.' . $detail['car_color']);
        $detail['emission'] = C('INT_EMISSION_STD.' . $detail['emission']);
        $detail['plate_prefix'] = C('PLATE_PREFIX.' . $detail['plate_prefix']);
        $detail['pointer_mileage'] = formatMileage($detail['pointer_mileage']);
        $detail['transfer_limit'] = C('TRANSFER_LIMIT.' . $detail['transfer_limit']);
        $detail['comefrom'] = Channel::get_full_name_by_id($detail['comefrom']);
        $detail['reserve_price'] = format_money($detail['reserve_price']);
        $detail['highest_price'] = $detail['bidding_best_price'] > $detail['bid_best_price'] ? $detail['bidding_best_price'] : $detail['bid_best_price'];
        if ($detail['is_consult'] == 1) {
            $detail['owner_trade_price'] = $detail['highest_price'] + $detail['company_subsidies'];
        } else {
            $detail['owner_trade_price'] = $detail['highest_price'];
        }
        $addr = new \AuctionCore\Other\Address();
        $detail['first_reg_city'] = $addr->get_name_by_code($detail['first_reg_city']);
        $detail['location_area'] = $addr->get_name_by_code($detail['location_area']);
        //付款状态
        if ($detail['pay_status'] == 1) {
            $detail['pay_status_name'] = "待付首款100%";
            $detail['pay_man'] = "--";
            $detail['pay_time'] = "--";
        } elseif ($detail['pay_status'] == 2) {
            $detail['pay_status_name'] = "已付首款100%";
            $paymentData = Car::getFirstPaymentBySid($detail['sid']);
            $detail['pay_man'] = $paymentData['emp_name'];
            $detail['pay_time'] = $paymentData['update_time'];
        }
        $detail['owner_type_name'] = C('OWNER_TYPE_NAME')[$detail['owner_type']];
        return $detail;
    }

    /**
     * 获取过户信息
     *
     * @return bool
     */
    public function get_transfer_info()
    {
        //要查询的详情
        $cols = "o.transfer_fee,c.car_source,c.sid,c.transfer_limit,o.transfer_type,o.is_other_channel_deal";
        $prefix = C('DB_PREFIX');
        $cond = ['o.order_id'=>$this->order_id ];
        $res = M('order')->alias('o')->field($cols)
            ->join('LEFT JOIN ' . $prefix . "cars as c ON c.car_id=o.car_id")
            ->where($cond)->find();

        //crl.invoice,crl.procedures_upload,
        if($res['car_source']==1){
            $carReturnInfo = CarReturn::getCarReturnInfoBySid($res['sid']);
            $res['invoice'] = $carReturnInfo['invoice'];
            $res['procedures_upload'] = empty($carReturnInfo['procedures_upload']) ? '无' : $carReturnInfo['procedures_upload'] ;
        }else{
            $res['invoice'] = "--";
            $res['procedures_upload'] = "无";
        }

        $res['transfer_limit'] = C("TRANSFER_LIMIT.".$res['transfer_limit']);
        $res['transfer_type'] = C("TRANSFER_TYPE.".$res['transfer_type']);
        return $res;
    }

    /**
     * 根据拍单号获取过户跟踪日志
     *
     * @return fix
     */
    public function get_transfer_follow_log()
    {
        $cols = "f.order_id,f.emp_id,f.remark,f.createtime,em.real_name";
        $prefix = C('DB_PREFIX');
        $cond = "f.order_id='" . $this->order_id . "'";
        $res = M('transfer_follow_log')->alias('f')->field($cols)
            ->join('LEFT JOIN ' . $prefix . "employee as em ON em.emp_id=f.emp_id")
            ->where($cond)->select();
// return M('order')->getLastSql();
        return $res;
    }

    /**
     * 获取过户图片
     *
     * @param  int $order_id
     *
     * @return  fix
     */
    public static function getTransferImg($order_id)
    {
        $transfer_img = M('transfer_img')->where('order_id = ' . $order_id)->select();
        return $transfer_img;
    }

    /**
     * 新老数据兼容获取过户图片
     *
     * @param  int $order_id
     *
     * @return  array
     */
    public static function getCarTransferImg($order_id)
    {   
        $map = [];
        $map['order_id'] = $order_id;
        $map['certificate_id'] = 0;
        $transfer_img = M('transfer_img')->where($map)->select();
        return $transfer_img;
    }


    /**
     * 获取成交车商信息
     */
    public function get_dealer_info()
    {
        $cols = "d.*,o.order_id";
        $prefix = C('DB_PREFIX');
        $map = [];
        $map['o.order_id'] = $this->order_id;
        $map['da.status'] = 0;
        $info = M('order')->alias('o')->field($cols)
            ->join($prefix . "dealer_auctioned as da ON da.order_id=o.order_id")
            ->join($prefix . "car_dealer as d ON d.dealer_id=da.dealer_id")
            ->where($map)->find();
        return $info;
    }

    /**
     * 获取拍单交付模式
     *
     * @return bool 1先付款后验车,2先验车后付款
     */
    public function get_dealer_pay_mode()
    {
        $info = $this->detail();
        $car = new Car($info['car_id']);
        $car_info = $car->detail();
        $branch_id = M("branch_city")->where("city_code=" . $car_info['location_area'])->getField("branch_id");
        $conf = SystemConf::getConfByName("DEALER_PAY_MODE_" . $branch_id);
        return $conf['value'];
    }

    /**
     * 获取拍单交付模式
     *
     * @return bool 1先付款后验车,2先验车后付款
     */
    public static function delivery_mode($car_id)
    {
        $car = new Car($car_id);
        $car_info = $car->detail();
        $branch_id = M("branch_city")->where("city_code=" . $car_info['location_area'])->getField("branch_id");
        $conf = SystemConf::getConfByName("DEALER_PAY_MODE_" . $branch_id);
        return $conf['value'];
    }

    //拍品查询 - 获取拍单与场次
    public static function get_order_and_scene($order_id)
    {
        $cols = 'o.*,c.location_area,c.car_source,c.delivery_mode,
                 os.name,arc.status as arc_status,di.status as di_status,oi.status as oi_status,
                 cdc.status as cdc_status,crl.status as crl_status,con.consult_status';
        $order = M('order')->alias('o')->field($cols)
            ->join(C('DB_PREFIX') . "cars as c ON o.`car_id` = c.`car_id`")
            ->join(C('DB_PREFIX') . "order_scene as os ON o.scene_id = os.scene_id")
            ->join("LEFT JOIN " . C('DB_PREFIX') . "recheck as arc ON o.`order_id` = arc.`order_id`")
            ->join("LEFT JOIN " . C('DB_PREFIX') . "dealer_issue as di ON o.`order_id` = di.`order_id`")
            ->join("LEFT JOIN " . C('DB_PREFIX') . "owner_issue as oi ON o.`order_id` = oi.`order_id`")
            ->join("LEFT JOIN " . C('DB_PREFIX') . "car_dealer_check as cdc ON o.`order_id` = cdc.`order_id`")
            ->join("LEFT JOIN " . C('DB_PREFIX') . "car_return_log as crl ON o.`order_id` = crl.`order_id`")
            ->join("LEFT JOIN " . C('DB_PREFIX') . "consult as con ON o.`order_id` = con.`order_id`")
            ->where(array('o.order_id' => $order_id))
            ->find();
        return $order;
    }

    /**
     * 获取拍品跟踪日志
     *
     * @return bool|mixed
     */
    public static function orderTraceLogById($order_id)
    {
        if ($order_id < 1) return false;
        return M("order_trace_log")->where("order_id=" . $order_id)->getField('action_log');
    }

    /**
     * 获取拍品出价排名
     *
     * @param $order_id
     *
     * @return array
     */
    public function get_order_biding_rank($order_id)
    {
        if (empty($order_id)) {
            return false;
        }
        /**
         * 投标价格 - 竞拍价格 - 出价排名
         */
        $bid_sub_query = M('bid_log')->where(array('order_id' => $order_id))->order('bid_id desc')->buildSql();
        $bid_log_rank = M()->table($bid_sub_query . ' bl')
            ->field('bl.dealer_id,bl.price,bl.createtime,cd.contact_person,du.uid')
            ->join(C('DB_PREFIX') . "car_dealer as cd ON bl.dealer_id=cd.dealer_id")
            ->join(C('DB_PREFIX') . "dealer_user as du ON cd.dealer_id=du.dealer_id")
            ->group('bl.dealer_id')
            ->where(array('order_id' => $order_id))
            ->select();
        if(!empty($bid_log_rank)){
            $dealer = new Dealer();
            $bid_log_rank= $dealer->get_contact_mobile_byAntNest($bid_log_rank);
        }
//        echo M()->getLastSql();
        $bid_log_rank_list = array();
        if (array_filter($bid_log_rank)) {
            foreach ($bid_log_rank as $kbi => $vbi) {
                $bid_log_rank_list[$kbi]['dealer_id'] = $vbi['dealer_id'];
                $bid_log_rank_list[$kbi]['price'] = $vbi['price'];
                $bid_log_rank_list[$kbi]['createtime'] = $vbi['createtime'];
                $bid_log_rank_list[$kbi]['dealer_name'] = $vbi['contact_person'];
                $bid_log_rank_list[$kbi]['contact_mobile'] = $vbi['contact_mobile'];
                $bid_log_rank_list[$kbi]['type'] = 1;
            }
        }
        $bidding_sub_query = M('bidding_log')->where(array('order_id' => $order_id))->order('bidding_id desc')->buildSql();
        $bidding_log_rank = M()->table($bidding_sub_query . ' bl')
            ->field('bl.dealer_id,bl.after_price,bl.createtime,cd.contact_person,du.uid')
            ->join(C('DB_PREFIX') . "car_dealer as cd ON bl.dealer_id=cd.dealer_id")
            ->join(C('DB_PREFIX') . "dealer_user as du ON cd.dealer_id=du.dealer_id")
            ->group('bl.dealer_id')
            ->where(array('order_id' => $order_id))
            ->select();
        if(!empty($bidding_log_rank)){
            $dealer = new Dealer();
            $bidding_log_rank= $dealer->get_contact_mobile_byAntNest($bidding_log_rank);
        }
//        echo M()->getLastSql();
        $bidding_log_rank_list = array();
        if (array_filter($bidding_log_rank)) {
            foreach ($bidding_log_rank as $kbd => $vbd) {
                $bidding_log_rank_list[$kbd]['dealer_id'] = $vbd['dealer_id'];
                $bidding_log_rank_list[$kbd]['price'] = $vbd['after_price'];
                $bidding_log_rank_list[$kbd]['dealer_name'] = $vbd['contact_person'];
                $bidding_log_rank_list[$kbd]['contact_mobile'] = $vbd['contact_mobile'];
                $bidding_log_rank_list[$kbd]['createtime'] = $vbd['createtime'];
                $bidding_log_rank_list[$kbd]['type'] = 2;
            }
        }
        $bid_history_rank = array();
        if (array_filter($bid_log_rank_list)) {
            $bid_history_rank = $bid_log_rank_list;
        }
        if (array_filter($bidding_log_rank_list)) {
            $bid_history_rank = $bidding_log_rank_list;
        }
        if (array_filter($bid_log_rank) && array_filter($bidding_log_rank)) {
            $bid_history_rank = array_merge($bid_log_rank_list, $bidding_log_rank_list);
        }
        $bid_history_rank_list = array();
        foreach ($bid_history_rank as $kbhr => $vbhr) {
            if (array_key_exists($vbhr['dealer_id'], $bid_history_rank_list)) {
                if ($bid_history_rank_list[$vbhr['dealer_id']]['price'] > $vbhr['price']) {
                    unset($vbhr);
                } else if ($bid_history_rank_list[$vbhr['dealer_id']]['price'] == $vbhr['price'] &&
                    $bid_history_rank_list[$vbhr['dealer_id']]['type'] < $vbhr['type']
                ) {
                    unset($vbhr);
                } else {
                    $bid_history_rank_list[$vbhr['dealer_id']] = $vbhr;
                }
            } else {
                $bid_history_rank_list[$vbhr['dealer_id']] = $vbhr;
            }
        }
        $bid_history_rank_data = array_values($this->bid_history_sort($bid_history_rank_list, 'price'));
//        dump($bid_history_rank_data);
        for ($i = 0, $length = count($bid_history_rank_data) - 1; $i < $length; $i++) {
            for ($j = 0; $j < $length - $i; $j++) {
                if ($bid_history_rank_data[$j]['price'] == $bid_history_rank_data[$j + 1]['price']) {
                    if ($bid_history_rank_data[$j]['type'] == $bid_history_rank_data[$j + 1]['type']) {
                        if (strtotime($bid_history_rank_data[$j]['createtime']) > strtotime($bid_history_rank_data[$j + 1]['createtime'])) {
                            $tmp = $bid_history_rank_data[$j];
                            $bid_history_rank_data[$j] = $bid_history_rank_data[$j + 1];
                            $bid_history_rank_data[$j + 1] = $tmp;
                        }
                    } elseif ($bid_history_rank_data[$j]['type'] > $bid_history_rank_data[$j + 1]['type']) {
                        $tmp = $bid_history_rank_data[$j];
                        $bid_history_rank_data[$j] = $bid_history_rank_data[$j + 1];
                        $bid_history_rank_data[$j + 1] = $tmp;
                    }
                }
            }
        }
//        dump($bid_history_rank_data);

        if (array_filter($bid_history_rank_data)) {
            $j = 1;
            $bid_history_rank_list_data = array();
            foreach ($bid_history_rank_data as $k => $v) {
                $bid_history_rank_list_data[$k]['sort'] = $j;
                $bid_history_rank_list_data[$k]['price'] = format_money($v['price']);
                $bid_history_rank_list_data[$k]['createtime'] = date("Y.m.d H:i:s", strtotime($v['createtime']));
                $bid_history_rank_list_data[$k]['dealer_name'] = $v['dealer_name'];
                $bid_history_rank_list_data[$k]['contact_mobile'] = $v['contact_mobile'];
                $bid_history_rank_list_data[$k]['type'] = $v['type'];
                $j++;
            }
        }
        return $bid_history_rank_list_data;
    }

    /**
     * 出价历史排序
     *
     * @param type $array
     * @param type $key
     * @param type $order
     *
     * @return type
     */
    private function bid_history_sort($array, $key, $order = 'desc')
    {
        $arr_nums = $arr = array();
        foreach ($array as $k => $v) {
            $arr_nums[$k] = $v[$key];
        }
        if ($order == 'desc') {
            arsort($arr_nums);
        } else {
            asort($arr_nums);
        }
        foreach ($arr_nums as $k => $v) {
            $arr[$k] = $array[$k];
        }
        return $arr;
    }

    /**
     *  获取拍单拍卖次数
     *
     * @param $order_id
     * return int
     */
    public function get_order_bidding_total($order_id)
    {
        if (empty($order_id)) {
            return false;
        }
        return M('order')->where(['order_id' => $order_id])->count();
    }

    /**
     * 取消贷款时间
     **/
    public function cancel_loan()
    {
        $map = array();
        $map['order_id'] = $this->order_id;
        $data = array();
        $data['canceltime'] = date('Y-m-d H:i:s');
        return M('loan_log')->where($map)->save($data);
    }

    /**
     * 获取对应拍单贷款的信息
     **/
    public function get_loan_log()
    {
        $where = array();
        $where['order_id'] = array('eq', $this->order_id);
        return M('loan_log')->where($where)->find();
    }

    /**
     * 修改对应拍单的信息
     **/
    public function update_loan_log($data)
    {
        $where = array();
        $where['order_id'] = array('eq', $this->order_id);
        return M('loan_log')->where($where)->save($data);
    }


    /**
     * 获取当前拍单 - 上个拍单的信息
     *
     * @param int $car_id
     * @param int $order_id
     *
     * @return array
     *
     */
    public static function get_last_order($car_id, $order_id)
    {
        if (intval($car_id) < 1 || intval($order_id) < 1) {
            return false;
        }
        $map['car_id'] = ['eq', $car_id];
        $map['order_id'] = ['neq', $order_id];
        return M('order')->where($map)->order('order_id DESC')->limit('1')->find();
    }

    /**
     * 获取当前车辆所有拍单
     */
    public static function get_all_order_id($car_id)
    {
        if (intval($car_id) < 1) {
            return false;
        }
        $map['car_id'] = ['eq', $car_id];
        $list = M('order')->where($map)->field('order_id')->order('order_id DESC')->select();
        $list_data = [];
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $list_data[$k] = $v['order_id'];
            }
        }
        return $list_data;
    }

    /**
     * 根据拍单ID找对应状态收款信息
     * @param   $data
     * @return   collection_id
     */
    public function getCollectionIdByOid()
    {
        $data = [];
        $data['c.payment_type'] = ['in', [1, 2, 3]];
        $data['oc.order_id'] = $this->order_id;
        $order_collection = M('order_collections')->alias('oc')
                            ->join(C('DB_PREFIX') . "collection as c ON oc.`collection_id` = c.`id`")
                            ->where($data)->find();
        return $order_collection['collection_id'];
    }

    /**
     * 根据拍单Id，锁定拍单
     * @return bool
     */
    public function lockByOrderId()
    {
        $arr = $this->detail();
        if ($arr['is_lock'] == '1') {
            return false;
        }
        return M('order')->where(['order_id' => $this->order_id])->save(['is_lock' => 1]);
    }

    /**
     * 根据拍单Id，解锁拍单
     * @return bool
     */
    public function unLockByOrderId()
    {
        $arr = $this->detail();
        if ($arr['is_lock'] != '1') {
            return false;
        }
        return M('order')->where(['order_id' => $this->order_id])->save(['is_lock' => 0]);
    }

    /**
     * 根据拍单Id，解锁拍单并且置成失败
     * @return bool
     */
    public function unLockFailByOrderId()
    {
        $arr = $this->detail();
        if ($arr['is_lock'] != '1') {
            return false;
        }
        // if ($arr['status'] == '12') {
        //     return false;
        // }
        return M('order')->where(['order_id' => $this->order_id])->save(['is_lock' => 0, 'status' => 12]);
    }

    /**
     * 根据拍单ID找对应采购单信息
     * @return array
     */
    public function getPurchaseByOrderId()
    {
        $map = [];
        $map['o.order_id'] = $this->order_id;
        $purchaseInfo = M('order')->alias('o')->field('po.*')
            ->join(C('DB_PREFIX') . "cars as c ON o.`car_id` = c.`car_id`")
            ->join(C('DB_PREFIX') . "purchase_order as po ON po.`sid` = c.`sid`")
            ->where($map)->find();
        return $purchaseInfo;
    }


    /**
     * 添加收款单拍单的关系
     *
     * @param int $orderId 拍单编号
     * @param int $collectionId 收款单编号
     * @param int $paymentType 收款单类型
     * @return mixed
     */
    public function addCollectionAndOrderRelation($orderId, $collectionId, $paymentType)
    {
        $data = [
            'order_id' => $orderId,
            'collection_id' => $collectionId,
            'payment_type' => $paymentType,
            'createtime' => date('Y-m-d H:i:s', time()),
        ];
        return M('order_collections')->add($data);
    }


    /**
     * 通过条件。得到收款单，拍单关系
     *
     * @param $condition 包括 order_id 拍单编号 payment_type 收款类型
     * @return mixed
     */
    public function getCollectionOrderRelationByCondition($condition)
    {
        return M('order_collections')->where($condition)->find();
    }

    /**
     * 创建订单编号
     *
     * @param $orderType 订单类型
     * @return string
     */
    public function createOrderNumber($orderType)
    {
        $date = date('Ymd', time());
        $randStr = $this->getRandString();
        $orderType = strlen($orderType) >= 10 ? $orderType : '0' . $orderType;
        $orderNu = 'D' . $orderType . $date . $randStr;

        $arr = $this->getOrderByOrderNu($orderNu);
        if (empty($arr)) { //如果根据订单编号，得不到订单，就表示不存在该订单号
            return $orderNu;
        } else {
            $this->createOrderNumber();
        }
    }


    /**
     * 获得随机字符串
     *
     * @return string
     */
    public function getRandString()
    {
        $s = substr(md5(uniqid(mt_rand(), true)), -4);
        if (preg_match('/^\d*$/', $s) || preg_match('/^[a-Z]*$/', $s)) {
            $this->getRandString();
        }
        return strtoupper($s);
    }

    /**
     * 根据订单编号，得到订单信息
     *
     * @param $orderNu
     * @return mixed
     */
    public function getOrderByOrderNu($orderNu)
    {
        $map['order_no'] = ['eq', $orderNu];
        return M('order')->where($map)->find();
    }


    /**
     * 添加订单信息
     *
     * @param array $data 订单数据
     * @return mixed
     */
    public static function add($data)
    {
        return M('order')->add($data);
    }


    /**
     * 得到旧的拍单数据
     * 初始化采购单使用
     *
     * @return mixed
     */
    public static function getOldOrder()
    {
        //select o.order_id,o.success_price,cars.car_source,cars.pay_status from au_order as o LEFT JOIN au_cars cars on o.car_id = cars.car_id where o.`status` in (7,8,9,10,11);
        /*SELECT
            o.order_id,
            o.`status`,
            o.car_id,
            o.success_price,
            cars.car_id,
            cars.car_source,
            cars.pay_status,
            cars.sid,
            cars.three_in_one,
            cars.is_self_receive
        FROM
            au_owner_confirm_log AS owner_confirm
        LEFT JOIN au_order AS o ON owner_confirm.order_id = o.order_id
        LEFT JOIN au_cars AS cars ON o.car_id = cars.car_id
        WHERE
            owner_confirm.result IN (1, 4)
            AND
            o.`status` >= 5
        ORDER BY
            o.`status` DESC;*/

        $fields = "o.order_id,o.order_no,o.success_price,o.status,o.fail_type,cars.car_id,cars.car_source,cars.pay_status,cars.sid,cars.three_in_one,cars.is_self_receive";
        $map['o.status'] = ['in', '7,8,9,10,11,12,13'];
        $map['o.is_other_channel_deal'] = ['eq', 0]; //不是其他渠道成交的车
        $map['owner_confirm.result'] = ['in', '1,4']; //车主确认成功和磋商成功的

        $data = M('owner_confirm_log')->alias('owner_confirm')->field($fields)
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'order o ON owner_confirm.order_id = o.order_id')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'cars cars ON o.car_id = cars.car_id')
            ->where($map)
            ->select();
        return $data;
    }


    /**
     * 添加
     **/
    public function addOrderFee($data)
    {
        $data['order_id'] = $this->order_id;
        $data['createtime'] = date('Y-m-d H:i:s');
        return M('order_fee')->add($data);
    }

    /**
     * 获取拍单相关费用
     * @param $order_id
     * @return bool|mixed
     */
    public static function getOrderFee($order_id)
    {
        $order_id = intval($order_id);
        if ($order_id < 1) return false;
        return M("order_fee")->where(['order_id' => $order_id])->find();
    }

    /**
     * 根据报告获取所有拍单ID
     * @param $carIds
     * @return array
     */
    public static function getOrderIdsByCarIds($carIds)
    {
        $orderIds = [];
        if (empty($carIds)) return $orderIds;
        $map = ['car_id' => ['in', $carIds]];
        $orders = M("order")->field('order_id')->where($map)->select();
        if (empty($orders)) return $orderIds;
        foreach ($orders as $order) {
            $orderIds[] = $order['order_id'];
        }
        return $orderIds;
    }


    /**
     * 通过Sid 得到最新的拍单信息
     *
     * @param $sid
     * @return mixed
     */
    public static function getNewestOrderBySid($sid)
    {
        $carArr = CarModel::getNewestCarBySid($sid);
        $carId = $carArr['car_id'];
        return M('order')->where(['car_id' => $carId])->order('order_id desc')->find();
    }


	/**
	 * 整理订单的状态，不是拍单
	 *
	 * @param $orderInfo 订单信息
	 * @return mixed
	 */
	public static function sortOrderStatus($orderInfo){
		$status =  $orderInfo['status'];
		switch ($status){
			case '8':
				$orderInfo['status_name'] = '待收款';
				break;
			case '9':
				$orderInfo['status_name'] = '待过户';
				break;
			case '10':
				$orderInfo['status_name'] = '过户中';
				break;
			case '13':
				$orderInfo['status_name'] = '已完成';
				break;
			default:
				$orderInfo['status_name'] = '已完成';
		}
		return $orderInfo;
	}


}
